package core;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import constants.Events;

public class EventBus {
	private transient final List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();

	/**
	 * 
	 * @param e
	 */
	public void handleEvent(ActionEvent e){
		firePropertyChange(stringToEvent(e.getActionCommand()).toString(), null, e.getSource());
	}
	
	public void handleEvent(String name, Object old, Object n){
		System.out.println("1. New: "+n);
		firePropertyChange(stringToEvent(name).toString(), old, n);
		System.out.println("End.");
	}
	
	/**
	 * Used to parse a string and translate it into an enumerated event
	 * that can be easily understood by other classes.
	 */
	private Events stringToEvent(String e){
		String s = e.toUpperCase();
		System.out.println("2.Raw event: "+s);
		s = s.replaceAll("\\s*",""); 
		Events[] es = Events.values();
		//System.out.println("EVENT: "+s);//test
		for(int i = 0; i < es.length; i++){
			if(es[i].toString().equals(s)){
				System.out.println("3. Parsed: "+es[i]);
				return es[i];
			}
		}
		return Events.ERROR;
	}
	
	public void addPropertyChangeListener (PropertyChangeListener listener) {
		listeners.add(listener);
	}

	public void removePropertyChangeListener (PropertyChangeListener listener) {
		listeners.remove(listener);
	}

	private void firePropertyChange (String property, Object oldValue, Object newValue) {

		if (oldValue == newValue || oldValue != null && oldValue.equals(newValue)) {
			return;
		}

		PropertyChangeEvent evt = new PropertyChangeEvent(this, property, oldValue, newValue);
		for (PropertyChangeListener listener : new ArrayList<PropertyChangeListener>(listeners)) {
			listener.propertyChange(evt);
		}
	}

}
